import webpack, { RuleSetUseItem, Configuration, WebpackPluginInstance } from 'webpack';
import LoadablePlugin from '@loadable/webpack-plugin';
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';
import TerserPlugin from 'terser-webpack-plugin';
import path from 'path';
export const isDev = process.env.NODE_ENV === 'development';

// loader
const getStyleLoaders = (isWeb: boolean, isSass?: boolean) => {
  let loaders: RuleSetUseItem[] = [
    {
      loader: 'css-loader',
      options: {
        importLoaders: isSass ? 2 : 1,
        modules: {
          auto: true,
          exportOnlyLocals: true,
        },
      },
    },
    {
      loader: 'postcss-loader',
    },
  ];
  if (isWeb) {
    loaders = [...loaders];
  }
  if (isSass) {
    loaders = [
      ...loaders,
      {
        loader: 'sass-loader',
      },
    ];
  }
  return loaders;
};

// plugin
const getPlugins = (isWeb: boolean) => {
  let plugins = [
    new webpack.ProgressPlugin(),
    new LoadablePlugin({
      writeToDisk: true,
      filename: '../loadable-state.json',
    }),
    // 定义全局变量
    new webpack.DefinePlugin({
      _CLIENT_: isWeb,
      _SERVER_: !isWeb,
      _DEV_: isDev,
    }),
  ];
  // 根据process.env NODE_ENV analyze
  if (!isWeb) {
    plugins = [
      ...plugins,
      new BundleAnalyzerPlugin({
        analyzerMode: process.env.NODE_ENV === 'analyze' ? 'server' : 'disabled',
      }),
    ];
  }
  return plugins;
};

const config = (isWeb: boolean): Configuration => ({
  mode: isDev ? 'development' : 'production',
  context: path.resolve(process.cwd()),
  // 压缩大小
  optimization: {
    minimizer: [
      new TerserPlugin({
        terserOptions: {
          compress: {
            drop_console: true,
          },
        },
      }),
    ],
  },
  plugins: getPlugins(isWeb) as WebpackPluginInstance[],
  module: {
    rules: [
      {
        test: /\.css$/,
        use: getStyleLoaders(isWeb),
      },
      {
        test: /\.(sass|scss)$/,
        use: getStyleLoaders(isWeb, true),
      },
    ],
  },
});

export default config;
